package com.gxl.butt.interceptor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.gxl.butt.service.IIPService;
import com.gxl.butt.utils.IPUtil;
import com.gxl.butt.utils.JSONUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.*;

import static com.gxl.butt.value.ErrorMsg.IP_ERROR;
import static com.gxl.butt.value.ErrorMsg.JSONUTIL_ERROR_CODE;

/**
 * Created by guoxiaolin on 2018/7/14.
 */
public class IpInterceptor extends HandlerInterceptorAdapter {
    //此处一般继承HandlerInterceptorAdapter适配器即可

    @Reference(interfaceClass = IIPService.class,timeout = 10000,check = false)
    private IIPService iipService;


    /**
     * 在DispatcherServlet之前执行
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String openid =request.getParameter("topic.openid");
        String ip = IPUtil.getIp(request);
        JSONObject resdata = iipService.getListByIpAndopenid(ip,openid);
        Integer resi = resdata.getInteger(JSONUTIL_ERROR_CODE);
        if (resi == 0){
            return true;
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("appplication/json");
        response.getWriter().append(JSONUtils.getRoot(-10000,IP_ERROR,ip).toJSONString());
        return false;

    }


    /**
     * 在controller执行之后的DispatcherServlet之后执行
     * */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("===========HandlerInterceptor1 postHandle");

    }

    /**
     * 在页面渲染完成返回给客户端之前执行
     * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        System.out.println("===========HandlerInterceptor1 afterCompletion");

    }
}